<?php
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE ^ E_DEPRECATED);

function sendData($socket, $data)
{
	$len = strlen($data);
	$ref = socket_write($socket, $data, $len);//发送数据	
	print "send data:[$$data] len:[$len], result:[$ref] \n";
	
	if($ref == false)
		getSocketError();
	
	return $ref;
}

function socketData($server, $port, $array)
{	
	$commonProtocol = getprotobyname('TCP');
	$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
	socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>1, "usec"=>0));
	
	$ref = socket_connect($socket, $server, $port);
	if($ref == false)
	{
		getSocketError();
		return;
	}
	
	$ref = sendData($socket, $array[0]);
	if($ref == false)
		return;
	
	$i=0;
	
	while(true)
	{
		$i++;
		print("\n\nloop: $i \n");
		sleep(1);
		
		if($i==2)
		{
			$ref = sendData($socket, $array[1]);
			if($ref == false)
				break;
		}
		
		if($i==5)
		{
			$ref = sendData($socket, $array[2]);
			if($ref == false)
				break;
		}
		
		$out = @socket_read($socket,4);
		if($out === false) 
		{ 			
			$err = getSocketError();
			if($err == 10054 || $err == 10053)  //服务端断开
				break;
			else
				continue; 
		}
		
		$out2 = unpack("I",$out);
		print("\nrecv length: $out2[1] \n");
		
		$out = @socket_read($socket,$out2[1]);
		print("recv content: $out \n");
		
		$rs = split(' ',$out);		
		print_r($rs);
	}
	socket_close($socket);
}

function dealData($data)
{
	return pack('I',strlen($data)).$data;	 
}

function getSocketError()
{
	$errorcode = socket_last_error();
	$errormsg = socket_strerror($errorcode);
	
	print("socket error: [$errorcode] $errormsg \n");
	
	return $errorcode;
}


$data1 = 'sys_login {"name":  "a", "pwd":"aa"}';
//$data2 = 'sys_login {"name":"b","pwd":"bb"}';

$data2 = 'enter_bar {}';
#$data3 = 'enter_bar {}';

$data3 = 'get_bar_list {"single":10,"double":5}';

socketData('127.0.0.1', 9999, array(dealData($data1), dealData($data2), dealData($data3)));

?>